#region [MainGameLoop Using Statements]
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using WP7_XNA_Accelerometer_Simulator.GameObjects.MovementControls;
using WP7_XNA_Accelerometer_Simulator.AccelerometerService;
using System.ServiceModel;
using WP7_XNA_Accelerometer_Simulator.Utils.Interoperability;
using WP7_XNA_Accelerometer_Simulator.Utils.GameInfo;
using WP7_XNA_Accelerometer_Simulator.Utils.Controls;
using WP7_XNA_Accelerometer_Simulator.GameObjects.SuperClasses;
using WP7_XNA_Accelerometer_Simulator.Utils.Rotation;
#endregion

namespace WP7_XNA_Accelerometer_Simulator
{
    /// <summary>
    /// This Class is responsible for the game initialization and main update-draw cycle
    /// </summary>
    public class MainGameLoop : Microsoft.Xna.Framework.Game
    {
        #region [MainGameLoop Constructor]
        /// <summary>
        /// MainGameLoop Constructor
        /// </summary>
        public MainGameLoop()
        {
            Content.RootDirectory = "Content";

            Window.Title = "Windows Phone 7 XNA Accelerometer Simulator";
            GraphicsDeviceManager gdm = new GraphicsDeviceManager(this);
            GameManager.GraphicsDeviceManager = gdm;
            GameManager.CameraPosition = new Vector3(0f, 9, 10f);
            GameManager.CameraLookAt = new Vector3(0f, 0f, 0f);
            //GameManager.CameraPosition = new Vector3(0f, 12, 0.1f);
            //GameManager.CameraLookAt = new Vector3(0f, 0f, 0f);
            GameManager.AccelerometerService = new AccelerometerServiceClient();
            GUI.CreateSimulatorEnvironment();
        }
        #endregion

        #region [MainGameLoop Initialize, LoadContent, UnloadContent, Update and Draw Methods]
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            base.Initialize();

            IsMouseVisible = true;
            GameManager.Cursor = new Cursor(this);
            Components.Add(GameManager.Cursor);

            GameManager.CameraViewMatrix = Matrix.CreateLookAt(GameManager.CameraPosition, GameManager.CameraLookAt, Vector3.Up);
            GameManager.CameraProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), 
                                                                                    GameManager.GraphicsDeviceManager.
                                                                                    GraphicsDevice.Viewport.AspectRatio, 1.0f, 10000.0f);

            GameManager.AccelerometerService.NotifyXNAStarted();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            GameManager.SpriteBatch = new SpriteBatch(GraphicsDevice);

            foreach (GameObject3D gameObject in GUI.GameObjects3D)
                gameObject.LoadContent(Content);

            /*Debug code*/
            //BoundingSphereRenderer.Initialize(GameManager.GraphicsDeviceManager.GraphicsDevice, 45);
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        /// <remarks>
        /// Closes the entire control panel and server if the simulator is closed.
        /// There's not point on having them running if the simulator was closed.
        /// </remarks>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
            ProcessUtil.CloseAccelerometerKit();
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            GameManager.CurrentMouseState = Mouse.GetState();
            GameManager.KeyboardState = Keyboard.GetState();

            ProcessKeyboard();

            foreach (GameObject3D gameObject in GUI.GameObjects3D)
            {
                gameObject.Update(gameTime);
            }
            GameManager.PreviousMouseState = GameManager.CurrentMouseState;
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            /*restore states*/
            GameManager.GraphicsDeviceManager.GraphicsDevice.BlendState = BlendState.Opaque;
            GameManager.GraphicsDeviceManager.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GameManager.GraphicsDeviceManager.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
            GameManager.GraphicsDeviceManager.GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

            foreach (GameObject3D gameObject in GUI.GameObjects3D)
            {
                gameObject.Draw(gameTime);
            }

            base.Draw(gameTime);
        }
        #endregion

        #region [MainGameLoop Private Methods]
        /// <summary>
        /// Interpretes and process keyboard input 
        /// </summary>
        private void ProcessKeyboard()
        {
            if (GameManager.KeyboardState.IsKeyDown(Keys.Left))
            {
                foreach (GameObject3D gameObject in GUI.GameObjects3D)
                {
                    gameObject.ProcessRotation(RotationUtil.RotationType.Pitch, 1);
                }
            }
            if (GameManager.KeyboardState.IsKeyDown(Keys.Right))
            {
                foreach (GameObject3D gameObject in GUI.GameObjects3D)
                {
                    gameObject.ProcessRotation(RotationUtil.RotationType.Pitch, -1);
                }
            }
            if (GameManager.KeyboardState.IsKeyDown(Keys.Up))
            {
                foreach (GameObject3D gameObject in GUI.GameObjects3D)
                {
                    gameObject.ProcessRotation(RotationUtil.RotationType.Roll, -1);
                }
            }
            if (GameManager.KeyboardState.IsKeyDown(Keys.Down))
            {
                foreach (GameObject3D gameObject in GUI.GameObjects3D)
                {
                    gameObject.ProcessRotation(RotationUtil.RotationType.Roll, 1);
                }
            }
            if (GameManager.KeyboardState.IsKeyDown(Keys.A))
            {
                foreach (GameObject3D gameObject in GUI.GameObjects3D)
                {
                    gameObject.ProcessRotation(RotationUtil.RotationType.Yaw, -1);
                }
            }
            if (GameManager.KeyboardState.IsKeyDown(Keys.D))
            {
                foreach (GameObject3D gameObject in GUI.GameObjects3D)
                {
                    gameObject.ProcessRotation(RotationUtil.RotationType.Yaw, 1);
                }
            }
        }
        #endregion
    }
}
